/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.scheduler;

import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Dpiendpointbean;
import cn.net.greenet.db.bean.Messageincominglog;
import cn.net.greenet.policysyn.ReportedVersionNormalizer;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author hedingwei
 */
public class IncominglogCleanerScheduler {

    
    public static IncominglogCleanerScheduler instance = null;

    private Timer timer = new Timer(IncominglogCleanerScheduler.class.getName());

    private IncominglogCleanerScheduler() {
    }

    public static IncominglogCleanerScheduler getInstance() {
        if (instance == null) {
            instance = new IncominglogCleanerScheduler();
        }
        return instance;
    }

    public void start() {
        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                Session session = null;
                Transaction tx = null;
                SessionFactory sf = null;
                try {
                    sf = HibernateUtil.getSessionFactory();
                    sf.getCache().evictEntityRegion(Messageincominglog.class);
                    session = sf.openSession();
                    tx = session.getTransaction();
                    session.beginTransaction();
                    Date time = new Date(System.currentTimeMillis() - 1 * 60 * 60 * 1000);
                    Query query = session.createQuery("delete Messageincominglog s where s.time < :limitTime");
                    query.setParameter("limitTime", time);
                    query.executeUpdate();
                    tx.commit();
                } catch (HibernateException e) {
                    tx.rollback();
                    e.printStackTrace();
                } finally {
                    if (session != null) {
                        session.close();
                    }
                }

            }
        }, 10000, 60000);
    }
}
